package com.farmer.h5.webview;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.View.OnLongClickListener;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.widget.ProgressBar;

import com.famer.h5.R;
import com.farmer.h5.net.HttpUtil;
import com.farmer.h5.util.PropertyUtil;
import com.farmer.h5.util.TipsToast;
import com.farmer.h5.webview.FWebViewClient.ClickTranfer;

/**
 * FarmerWebView 自定义WebView
 * 
 * @author zhu_qiang1
 */
public class FarmerWebView extends WebView implements I_WebSetting, OnKeyListener, OnLongClickListener
{
    /**
     * 设置项
     */
    private FWebSettings fwebSettings;
    
    /**
     * WebSettings
     */
    public WebSettings webSettings;
    
    /**
     * 上下文
     */
    private Context context;
    
    /**
     * 自定义WebViewClient
     */
    public FWebViewClient fWebViewClient;
    
    /**
     * 自定义WebChromeClient
     */
    public FWebChromeClient fWebChromeClient;
    
    /**
     * 加载进度条
     */
    private ProgressBar progressbar;
    
    /**
     * 构造函数
     */
    @SuppressWarnings("deprecation")
    public FarmerWebView(Context context)
    {
        super(context);
        this.context = context;
        fwebSettings = PropertyUtil.getPropertiesURL(context);
        webSettings = this.getSettings();
        // 注册长按事件
        this.setOnLongClickListener(this);
        // 注册按键监听事件
        this.setOnKeyListener(this);
        
        // 判断是否显示加载条
        if (fwebSettings.isShowLoading)
        {
            progressbar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
            progressbar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 14, 0, 0));
            // 设置进度条样式
            Drawable drawable = context.getResources().getDrawable(R.drawable.progress_bar_states);
            progressbar.setProgressDrawable(drawable);
            addView(progressbar);
        }
        setWebViewSetting();
        setWebViewUserAgent();
        setWebViewChromClient();
        setWebClient();
    }
    
    /**
     * 构造函数
     */
    @SuppressWarnings("deprecation")
    public FarmerWebView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        this.context = context;
        fwebSettings = PropertyUtil.getPropertiesURL(context);
        webSettings = this.getSettings();
        // 注册长按事件
        this.setOnLongClickListener(this);
        // 注册按键监听事件
        this.setOnKeyListener(this);
        
        // 判断是否显示加载条
        if (fwebSettings.isShowLoading)
        {
            progressbar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
            progressbar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 14, 0, 0));
            // 设置进度条样式
            Drawable drawable = context.getResources().getDrawable(R.drawable.progress_bar_states);
            progressbar.setProgressDrawable(drawable);
            addView(progressbar);
        }
        
        setWebViewSetting();
        setWebViewUserAgent();
        setWebViewChromClient();
        setWebClient();
    }
    
    @SuppressLint("SetJavaScriptEnabled")
    @Override
    public void setWebViewSetting()
    {
        // 屏幕自动适配
        webSettings.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        
        // 开启js
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        
        // 是否可以放大
        if (fwebSettings.isZoom)
        {
            webSettings.setSupportZoom(true);
        }
        else
        {
            webSettings.setSupportZoom(false);
        }
        
        // 是否显示放大\缩小控件
        if (fwebSettings.isShowZoomControll)
        {
            // webSettings.setBuiltInZoomControls(true);
            webSettings.setDisplayZoomControls(true);
        }
        else
        {
            // webSettings.setBuiltInZoomControls(false);
            webSettings.setDisplayZoomControls(false);
        }
        
        // 是否使用缓存
        if (fwebSettings.isUseCache)
        {
            // 优先使用缓存
            webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }
        else
        {
            // 不使用缓存
            webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        }
        
        // 是否开启GPS定位
        if (fwebSettings.isUseGps)
        {
            webSettings.setDatabaseEnabled(true);
            // 数据库创建目录
            String dir = context.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
            // 启用地理定位
            webSettings.setGeolocationEnabled(true);
            // 设置定位的数据库路径
            webSettings.setGeolocationDatabasePath(dir);
            // 最重要的方法，一定要设置，这就是出不来的主要原因
            webSettings.setDomStorageEnabled(true);
        }
    }
    
    /**
     * 设置webView的userAgent
     */
    @Override
    public void setWebViewUserAgent()
    {
        if (!TextUtils.isEmpty(fwebSettings.userAgent))
        {
            // 设置浏览器的UserAgent
            webSettings.setUserAgentString(webSettings.getUserAgentString() + fwebSettings.userAgent);
        }
    }
    
    /**
     * 设置WebView的WebViewChromClient
     */
    @Override
    public void setWebViewChromClient()
    {
        fWebChromeClient = new FWebChromeClient();
        // 设置项
        fWebChromeClient.setProperty(fwebSettings, context);
        // 显示加载进度条
        if (fwebSettings.isShowLoading)
        {
            fWebChromeClient.setProgressbar(progressbar);
        }
        // 设置
        setWebChromeClient(fWebChromeClient);
    }
    
    public FWebChromeClient getWebViewChromClient()
    {
        return fWebChromeClient;
    }
    
    /**
     * 设置WebView的WebViewClient
     */
    @Override
    public void setWebClient()
    {
        fWebViewClient = new FWebViewClient();
        fWebViewClient.setcTranfer(new ClickTranfer()
        {
            
            @Override
            public void loadListener(WebView view, String url)
            {
                floadListener(url);
            }
            
            @Override
            public void finishListener(WebView view, String url)
            {
                ffinishListener(url);
            }
            
            @Override
            public void startListener(WebView view, String url, Bitmap favicon)
            {
                fstartListener(url);
            }
            
            @Override
            public void receivedErrorListener(WebView view, int errorCode, String description, String failingUrl)
            {
                freceivedErrorListener(view, errorCode, description, failingUrl);
            }
        });
        
        setWebViewClient(fWebViewClient);
    }
    
    public void floadListener(String url)
    {
        this.loadUrl(url);
    }
    
    public void ffinishListener(String url)
    {
        
    }
    
    public void fstartListener(String url)
    {
        
    }
    
    public void freceivedErrorListener(WebView view, int errorCode, String description, String failingUrl)
    {
        if (!TextUtils.isEmpty(fwebSettings.errorHtml))
        {
            // 屏蔽系统默认的 404 样式
            loadUrl("javascript:document.body.innerHTML=''");
            // 加载本地的一个错误页面
            loadUrl("file:///android_asset/" + fwebSettings.errorHtml);
        }
    }
    
    @Override
    public boolean onLongClick(View v)
    {
        return true;
    }
    
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event)
    {
        if (event.getAction() == KeyEvent.ACTION_DOWN)
        {
            if (keyCode == KeyEvent.KEYCODE_BACK && fwebSettings.isCanPressBack)
            {
                fGoBack();
            }
            else
            {
                return false;
            }
        }
        return true;
    }
    
    /**
     * 返回按钮
     */
    public void fGoBack()
    {
        if (canGoBack())
        {
            goBack();
        }
        else
        {
            ((Activity)context).finish();
        }
    }
    
    @Override
    public void loadUrl(String url)
    {
        if (!HttpUtil.isNetWork(context) && !url.equals("javascript:document.body.innerHTML=''")
            && !url.equals("javascript:document.body.innerHTML=''")
            && !url.equals("file:///android_asset/" + fwebSettings.errorHtml))
        {
            TipsToast.makeText(context, "当前没有可用网络", TipsToast.LENGTH_SHORT).show();
        }
        super.loadUrl(url);
    }
    
    @SuppressWarnings("deprecation")
    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt)
    {
        LayoutParams lp = (LayoutParams)progressbar.getLayoutParams();
        lp.x = l;
        lp.y = t;
        progressbar.setLayoutParams(lp);
        super.onScrollChanged(l, t, oldl, oldt);
    }
}
